const db = require("../db/index");

// 新增分类
exports.addClass = (req, res) => {
  let { class_name } = req.body;
  let sqlStr = `select * from goods_classification where class_name = ?`;
  db.query(sqlStr, class_name, (err, results) => {
    if (err) return res.cc(err);
    if (results.length < 1) {
      sqlStr = `insert into goods_classification (class_name) values (?)`;
      db.query(sqlStr, class_name, (err, results) => {
        console.log(err);
        if (err) return res.cc(err);
        if (results.affectedRows === 1) {
          res.send("添加分类成功！");
        } else {
          res.cc("添加分类失败");
        }
      });
    } else {
      res.send("你需要添加的分类已存在");
    }
  });
};

// 查询分类
exports.queryClass = (req, res) => {
  let sqlStr = `select * from goods_classification`;
  db.query(sqlStr, (err, results) => {
    if (err) return res.cc(err);
    res.send(results);
  });
};
// 新增商品
exports.addGood = (req, res) => {
  let { classification, good_name, good_detail } = req.body;
  let sqlStr = `insert into goods (classification, good_name, good_detail) values (?,?,?)`;
  db.query(sqlStr, [classification, good_name, good_detail], (err, results) => {
    console.log(err);
    if (err) return res.cc(err);
    if (results.affectedRows === 1) {
      res.send("添加商品成功！");
    } else {
      res.cc("添加商品失败");
    }
  });
};

// 查询商品
exports.queryGood = (req, res) => {
  let sqlStr = `select * from goods`;
  db.query(sqlStr, (err, results) => {
    if (err) return res.cc(err);
    res.send(results);
  });
};
